from flask import Flask,request,redirect,render_template
import os


app  = Flask(__name__)
UPLOAD_FOLDER = 'static/prototypes'

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 200 * 1024 * 1024 # 200MB

#文件上传
@app.route('/upload', methods=['GET','POST'])
def upload_prototype():
    if request.method == 'GET':
        return render_template('upload.html')
    else:
        if 'prototype' not in request.files:
            return {'error':' 未选择文件'} ,400
        file = request.files['prototype']
        if file.filename == '':
            return {'error':' 空文件名'} ,400
        else:
            filename = file.filename
            folder_name = f"{secure_filename(file.filename)}"
            target_dir = os.path.join(app.config['UPLOAD_FOLDER'], folder_name)
            os.makedirs(target_dir, exist_ok=True)

            zip_path = os.path.join(target_dir, filename)
            file.save(zip_path)

            import patoolib
            patoolib.extract_archive(zip_path, outdir=target_dir)
            os.remove( zip_path)

            entry_file = 'index.html'
            for f in os.listdir(target_dir):
                if f.endswith('.html') and f.lower() in ['index.xhtml','start.html']:

                    entry_file = f
                    break
            return {'entry':entry_file},200

#查看    
@app.route('/view', methods=['GET'])
def view_prototype():
        if 'prototype' not in request.files:
            return {'error':' 未选择文件'} ,400
        file = request.files['prototype']
        if file.filename == '':
            return {'error':' 空文件名'} ,400
        else:
            filename = secure_filename(file.filename)
        return render_template('view.html', prototype=f"/static/prototypes/{folder_name}/{entry_file}")

if __name__ == '__main__':
    os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
    app.run(host='0.0.0.0', port=5000, debug=True)